package main

import (
	"context"
	"fmt"

	"github.com/topfreegames/pitaya/v2"
	"github.com/topfreegames/pitaya/v2/acceptor"
	"github.com/topfreegames/pitaya/v2/cluster"
	"github.com/topfreegames/pitaya/v2/config"
	"github.com/topfreegames/pitaya/v2/route"
	"github.com/topfreegames/pitaya/v2/serialize/protobuf"

	pkgconfig "webgame/pkg/config"
)

func main() {

	setting, vipErr := pkgconfig.NewServerConfig("connector.yaml")

	if vipErr != nil {
		panic(vipErr)
	}

	defer pitaya.Shutdown()

	config := config.NewDefaultPitayaConfig()
	builder := pitaya.NewDefaultBuilder(true, "connector", pitaya.Cluster, map[string]string{}, *config)

	tcp := acceptor.NewTCPAcceptor(fmt.Sprintf(":%d", setting.System.Addr))

	builder.AddAcceptor(tcp)

	builder.Serializer = protobuf.NewSerializer()

	pitaya := builder.Build()

	err := pitaya.AddRoute("hall", func(
		ctx context.Context,
		route *route.Route,
		payload []byte,
		servers map[string]*cluster.Server,
	) (*cluster.Server, error) {
		// will return the first server
		for k := range servers {
			return servers[k], nil
		}
		return nil, nil
	})

	if err != nil {
		fmt.Printf("error adding route %s\n", err.Error())
	}

	err = pitaya.SetDictionary(map[string]uint16{
		"connector.getsessiondata": 1,
		"connector.setsessiondata": 2,
		"room.room.getsessiondata": 3,
		"onMessage":                4,
		"onMembers":                5,
	})

	if err != nil {
		fmt.Printf("error setting route dictionary %s\n", err.Error())
	}

	pitaya.Start()
}
